const router = require('koa-router')()
const DB = require('../db')
const { SECRETKEY, expiresIn } = require('../token.config')
const md5 = require('blueimp-md5')

router.prefix('/questions')

/**发布问题 */
router.post('/publish', async (ctx, next) => {
  const userName = ctx.request.header.username
  if (!userName) {
    ctx.body = {
      code: '0012',
      msg: '缺少请求头参数',
      data: false
    }
    return
  }
  const { title, mdContent, cateTags, rewardGmoney } = ctx.request.body
  if (!title || mdContent === undefined || !cateTags || rewardGmoney === undefined) {
    ctx.body = {
      code: '0002',
      msg: '缺少必要参数',
      data: false
    }
    return
  }
  if (typeof rewardGmoney !== 'number') {
    ctx.body = {
      code: '0001',
      msg: '传入参数数据类型不正确',
      data: false
    }
    return
  }
  await DB.add('questions', {
    questionId: `${md5(userName + '_' + Date.now())}`, // 问题唯一标识
    userName, // 用户名
    publishDate: Date.now(), // 问题发布时间
    title, // 标题
    mdContent, // 问题md格式内容
    cateTags, // 分类标签名
    rewardGmoney, // 悬赏G币
    isResolved: false, // 问题是否被解决
    focusNames: [], //关注该问题的人用户名列表
    answerNumbersSincePublish: 0, // 发布问题后的总回答数，含被删除的问题数
    answers: [], // 该问题下的回答
  })
  // 扣除发布者的G币
  const r = await DB.find('users', { userName })
  const g = r[0].gMoney
  const t = r[0].totalConsume
  await DB.updateValue('users', { userName }, {
    gMoney: g - rewardGmoney,
    totalConsume: t + rewardGmoney
  })

  // 发布者增加消费记录
  await DB.updateDeep('users', { userName }, {
    consumeDetails: {
      consumeDate: Date.now(), // 消费日期
      orderId: 'X' + Date.now(), // 消费订单号
      consumeName: '问题', // 消费商品名称
      consumeAmount: rewardGmoney, // 消费G币数量
      consumeChannel: '发布问题', // 消费渠道
      consumeStatus: '已处理', // 订单状态
    }
  })

  ctx.body = {
    code: '0000',
    msg: '发布成功',
    data: true
  }
})

/**
 * 获取不同类型的问题
 * @type 1:全部问题 2:未解决 3:已解决 4:我发布的 5:我回答的 6:我关注的
 */
router.get('/receive', async (ctx, next) => {
  const { type } = ctx.request.query
  const userName = ctx.request.header.username
  
  if (!type) {
    ctx.body = {
      code: '0002',
      msg: '缺少必要参数',
      data: false
    }
    return
  }
  const t = Number(type)
  if (t === 1) {
    const r = await DB.findAll('questions')
    ctx.body = {
      code: '0000',
      msg: '获取成功',
      data: r
    }
  } else if (t === 2) {
    const r = await DB.find('questions', { isResolved: false })
    ctx.body = {
      code: '0000',
      msg: '获取成功',
      data: r
    }
  } else if (t === 3) {
    const r = await DB.find('questions', { isResolved: true })
    ctx.body = {
      code: '0000',
      msg: '获取成功',
      data: r
    }
  } else if (t === 4) {
    const r = await DB.find('questions', { userName })
    ctx.body = {
      code: '0000',
      msg: '获取成功',
      data: r
    }
  } else if (t === 5) {
    const r = await DB.find('questions', {
      'answers.answerUserName': {
      $eq: userName
    } })
    ctx.body = {
      code: '0000',
      msg: '获取成功',
      data: r
    }
  } else if (t === 6) {
    const r = await DB.find('questions', {
      focusNames: {
        $in: [userName]
      }})
    ctx.body = {
      code: '0000',
      msg: '获取成功',
      data: r
    }
  } else {
    const r = await DB.find('questions', { questionId: type })
    ctx.body = {
      code: '0000',
      msg: '获取成功',
      data: r
    }
  }
})

/**提交回答 */
router.post('/submitAnswer', async (ctx, next) => {
  const userName = ctx.request.header.username
  if (!userName) {
    ctx.body = {
      code: '0012',
      msg: '缺少请求头参数',
      data: false
    }
    return
  }
  const { answerMdContent, nick, questionId } = ctx.request.body
  if (!answerMdContent || answerMdContent.trim().length === 0 || !nick || !questionId) {
    ctx.body = {
      code: '0002',
      msg: '缺少必要参数',
      data: false
    }
    return
  }
  const r = await DB.find('questions', { questionId })
  if (r.length === 0) {
    ctx.body = {
      code: '0013',
      msg: '未查询到指定内容',
      data: false
    }
    return
  }
  const { answerNumbersSincePublish } = r[0]
  const newNumber = answerNumbersSincePublish + 1
  await DB.updateValue('questions', { questionId }, { answerNumbersSincePublish: newNumber })
  await DB.updateDeep('questions', { questionId }, {
    answers: {
      answerMdContent, // 回答的内容
      answerUserName: userName, // 答友用户名
      nick, // 答友昵称
      answerDate: Date.now(), // 回答时间
      answerId: String(newNumber), // 该回答的唯一id及编号
      isAccepted: false // 该回答是否被问友采纳
    }
  })
  // 增加答题总数
  const r1 = await DB.find('users', { userName })
  const t1 = r1[0].totalAnswerNumbers
  await DB.updateValue('users', { userName }, { totalAnswerNumbers : t1 + 1 })
  ctx.body = {
    code: '0000',
    msg: '回答成功',
    data: true
  }
})

/**采纳回答 */
router.post('/accept', async (ctx, next) => {
  const userName = ctx.request.header.username
  if (!userName) {
    ctx.body = {
      code: '0012',
      msg: '缺少请求头参数',
      data: false
    }
    return
  }
  const { questionId, answerId } = ctx.request.body
  if (!questionId || !answerId) {
    ctx.body = {
      code: '0002',
      msg: '缺少必要参数',
      data: false
    }
    return
  }
  const r = await DB.findInArr('questions', 'answers.answerId', answerId)
  if (!r || r.length === 0) {
    ctx.body = {
      code: '0013',
      msg: '未查询到指定内容',
      data: false
    }
    return
  }
  
  // 点击第几个答案的采纳，就把该答案的isAccepted设置为true
  await DB.updateInSortDeep('questions', { questionId }, {
    [`answers.${parseInt(answerId) - 1}.isAccepted`] : true
  })
  // 采纳后把isResolved设置为true
  await DB.updateValue('questions', { questionId }, { isResolved: true })

  const r1 = await DB.find('questions', { questionId })
  if (r1.length === 0) {
    ctx.body = {
      code: '0013',
      msg: '未查询到指定内容',
      data: false
    }
    return
  }
  // 回答者的用户名
  const a = r1[0].answers[parseInt(answerId) - 1].answerUserName
  // 问题悬赏G币数量
  const n = r1[0].rewardGmoney
  const r2 = await DB.find('users', { userName: a })
  if (r2.length === 0) {
    ctx.body = {
      code: '0013',
      msg: '该答友不存在',
      data: false
    }
    return
  }

  const _g = r2[0].gMoney
  const a1 = r2[0].acceptionNumbers
  const g1 = r2[0].gMoneyFromAnswers

  await DB.updateValue('users', { userName: a }, {
    gMoney: _g + n,
    acceptionNumbers: a1 + 1,
    gMoneyFromAnswers: g1 + n
  })

  ctx.body = {
    code: '0000',
    msg: '采纳成功',
    data: true
  }
})

/**关注该问题 */
router.post('/focus', async (ctx, next) => {
  const userName = ctx.request.header.username
  if (!userName) {
    ctx.body = {
      code: '0012',
      msg: '缺少请求头参数',
      data: false
    }
    return
  }
  const { questionId } = ctx.request.body
  if (!questionId) {
    ctx.body = {
      code: '0002',
      msg: '缺少必要参数',
      data: false
    }
    return
  }
  const r = await DB.find('questions', { questionId })
  if (r.length === 0) {
    ctx.body = {
      code: '0013',
      msg: '未查询到指定内容',
      data: false
    }
    return
  }
  if (!r[0].focusNames) {
    await DB.updateValue('questions', { questionId }, { focusNames: [userName]})
  } else {
    await DB.updateDeep('questions', { questionId }, { focusNames: userName})
  }
  // const r1 = await DB.find('questions', { questionId })
  ctx.body = {
    code: '0000',
    msg: '关注成功',
    data: true
  }
})

module.exports = router